package com.jiamao.goplay.ui.discover.vm;

import android.app.Application;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableArrayList;
import androidx.databinding.ObservableList;

import com.amap.api.location.AMapLocation;
import com.jiamao.goplay.BR;
import com.jiamao.goplay.R;
import com.jiamao.goplay.app.AppApplication;
import com.jiamao.goplay.bean.BaseRep;
import com.jiamao.goplay.bean.FindItem;
import com.jiamao.goplay.bean.NearbyItem;
import com.jiamao.goplay.bean.res.ResFind;
import com.jiamao.goplay.bean.res.ResMatch;
import com.jiamao.goplay.bean.res.ResNearbyList;
import com.jiamao.goplay.bean.res.ResUserInfoDetail;
import com.jiamao.goplay.config.Config;
import com.jiamao.goplay.data.BaseSubscriber;
import com.jiamao.goplay.data.DataRepository;
import com.jiamao.goplay.ui.discover.MatchFragment;
import com.jiamao.goplay.util.GsonUtil;
import com.tamsiree.rxkit.view.RxToast;

import java.io.Serializable;
import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.observers.DisposableObserver;
import me.goldze.mvvmhabit.base.BaseViewModel;
import me.goldze.mvvmhabit.base.MultiItemViewModel;
import me.goldze.mvvmhabit.binding.command.BindingAction;
import me.goldze.mvvmhabit.binding.command.BindingConsumer;
import me.goldze.mvvmhabit.bus.Messenger;
import me.goldze.mvvmhabit.bus.event.SingleLiveEvent;
import me.goldze.mvvmhabit.utils.RxUtils;
import me.tatarka.bindingcollectionadapter2.ItemBinding;
import me.tatarka.bindingcollectionadapter2.OnItemBind;

public class FindVM extends BaseViewModel<DataRepository> {

    private int page = 1;
    private int count = 0;
    public int sex = 0;
    public FindVM(@NonNull Application application, DataRepository repository) {
        super(application, repository);
        //模拟10个条目，数据源可以来自网络
//        for (int i = 0; i < 20; i++) {
//
//            FindItemVM item = new FindItemVM(this);
//            observableList.add(item);
//
//        }


        Messenger.getDefault().register(this, Config.MGER_LOCATION_ADDR, AMapLocation.class, new BindingConsumer<AMapLocation>() {
            @Override
            public void call(AMapLocation aMapLocation) {
                Log.d("HTML","FindVM BBBBBBBBBBBBBBBBBBBBBB");
                uc.uiInitRefreshEvent.setValue(0);
                getLoadInitData();
            }


        });

        Messenger.getDefault().register(this, Config.MGER_LOCATION_TYPE, Integer.class, new BindingConsumer<Integer>() {
            @Override
            public void call(Integer aMapLocation) {
                Log.d("HTML","AAAAAAAA");
                    if (aMapLocation == 1){
                        uc.uiInitRefreshEvent.setValue(4);
                }
            }




        });

    }
    //封装一个界面发生改变的观察者
    public UIChangeObservable uc = new UIChangeObservable();

    public class UIChangeObservable {
        //密码开关观察者
        public SingleLiveEvent<Integer> pSwitchEvent = new SingleLiveEvent<>();
        public SingleLiveEvent<Integer> uiInitRefreshEvent = new SingleLiveEvent<>();
        public SingleLiveEvent<Integer> refreshEvent = new SingleLiveEvent<>();
        public SingleLiveEvent<String> startChat = new SingleLiveEvent<>();
    }


    //给RecyclerView添加ObservableList
    public ObservableList<MultiItemViewModel> observableList = new ObservableArrayList<>();
    //RecyclerView多布局添加ItemBinding
    public ItemBinding<MultiItemViewModel> itemBinding = ItemBinding.of(new OnItemBind<MultiItemViewModel>() {
        @Override
        public void onItemBind(ItemBinding itemBinding, int position, MultiItemViewModel item) {
            //通过item的类型, 动态设置Item加载的布局
            String itemType = (String) item.getItemType();

            itemBinding.set(BR.viewModel, R.layout.discover_find_item_layout);     //123阿萨德 按时
        }
    });


    public void getLoadInitData(){
        //uc.pSwitchEvent.setValue();
        page = 1;
        model.getApi().findList(AppApplication.getInstance().lat,AppApplication.getInstance().lot,Config.PAGELIMT,page,sex)
                .compose(RxUtils.bindToLifecycle(getLifecycleProvider())) // 请求与View周期同步
                .compose(RxUtils.schedulersTransformer())  // 线程调度
                //   .compose(RxUtils.exceptionTransformer())   // 网络错误的异常转换
                //    .doOnSubscribe(this) //请求与ViewModel周期同步
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        uc.uiInitRefreshEvent.setValue(1);
                        uc.refreshEvent.setValue(0);
                    }
                })
                .subscribe(new BaseSubscriber<BaseRep<ResFind>>() {
                    @Override
                    public void onNext(BaseRep<ResFind> baseRep) {
                        super.onNext(baseRep);
                        uc.refreshEvent.setValue(0);
                        if (baseRep.isOk()){

                            observableList.clear();
                            if (baseRep.getData()==null){
                                uc.uiInitRefreshEvent.setValue(3);
                                return;
                            }
                            count = baseRep.getData().getTotal();
                            if (baseRep.getData().getList().size() ==0 ){
                                observableList.clear();
                                uc.uiInitRefreshEvent.setValue(3);
                                return;
                            }
                            uc.uiInitRefreshEvent.setValue(0);
                            for (FindItem item: baseRep.getData().getList()){
                               FindItemVM items = new FindItemVM(FindVM.this,item);
                                observableList.add(items);
                            }

//                                uc.reBtnGetCode.setValue(false);
                            //  reTimeSmsCode();
                        }else {
                            uc.uiInitRefreshEvent.setValue(2);
                            // RxToast.showToastShort(baseRep.getMsg());
//
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        //  dismissDialog();
                        uc.refreshEvent.setValue(0);
                        uc.uiInitRefreshEvent.postValue(2);
                        e.printStackTrace();
                        RxToast.showToastShort("网络出现故障");
                    }

                    @Override
                    public void onComplete() {
                        //   dismissDialog();
                    }

                });

    }


    public void getLoadData(int i){
        //uc.pSwitchEvent.setValue();
        if (count == observableList.size()){
            getLoadInitData();
            return;
        }
        if (i == 0){
            page = 0;
        }
        page++;
        model.getApi().findList(AppApplication.getInstance().lat,AppApplication.getInstance().lot,Config.PAGELIMT,page,sex)
                .compose(RxUtils.bindToLifecycle(getLifecycleProvider())) // 请求与View周期同步
                .compose(RxUtils.schedulersTransformer())  // 线程调度
                   .compose(RxUtils.exceptionTransformer())   // 网络错误的异常转换
                //    .doOnSubscribe(this) //请求与ViewModel周期同步
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        uc.refreshEvent.setValue(1);
                        //      showDialog();
                        // dialog.show();
                    }
                })
                .subscribe(new BaseSubscriber<BaseRep<ResFind>>() {
                    @Override
                    public void onNext(BaseRep<ResFind> baseRep) {
                        super.onNext(baseRep);
                        uc.refreshEvent.setValue(0);
                        if (baseRep.isOk()){
                            if (i==0){
                                observableList.clear();
                            }
                            if (baseRep.getData()==null){
                                uc.uiInitRefreshEvent.setValue(3);
                                return;
                            }
                            count = baseRep.getData().getTotal();
                            if (baseRep.getData().getList().size() ==0 ){
                                observableList.clear();
                                uc.uiInitRefreshEvent.setValue(3);
                                return;
                            }
                            for (FindItem item: baseRep.getData().getList()){
                               FindItemVM items = new FindItemVM(FindVM.this,item);
                                observableList.add(items);
                            }

//                                uc.reBtnGetCode.setValue(false);
                            //  reTimeSmsCode();
                        }else {
                            uc.refreshEvent.setValue(2);
                            // RxToast.showToastShort(baseRep.getMsg());
//
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        //  dismissDialog();
                        uc.refreshEvent.setValue(2);
                        e.printStackTrace();
                        RxToast.showToastShort("网络出现故障");
                    }

                    @Override
                    public void onComplete() {
                        //   dismissDialog();
                    }

                });
    }



    public void yaoqing(String id,String  uid,FindItemVM vm){
        //uc.pSwitchEvent.setValue();

        BaseSubscriber subscription =  new BaseSubscriber<BaseRep>() {
            @Override
            public void onNext(BaseRep baseRep) {
                super.onNext(baseRep);
                dismissDialog();
                if (baseRep.isOk()){
                    vm.yyqBtnVisibility.set(View.VISIBLE);
                    vm.yqBtnVisibility.set(View.GONE);
                    vm.yqnBtnVisibility.set(View.GONE);
                }else {
                    RxToast.showToastShort(baseRep.getMsg());
                }

            }

            @Override
            public void onError(Throwable e) {
                dismissDialog();
                //   uc.pSwitchEvent.setValue(2);
                e.printStackTrace();
                RxToast.showToastShort("网络出现故障");
            }

            @Override
            public void onComplete() {
                //   dismissDialog();
            }

        };

        model.getApi().invitingHe(id,uid)
                .compose(RxUtils.bindToLifecycle(getLifecycleProvider())) // 请求与View周期同步
                .compose(RxUtils.schedulersTransformer())  // 线程调度
                //   .compose(RxUtils.exceptionTransformer())   // 网络错误的异常转换
                //    .doOnSubscribe(this) //请求与ViewModel周期同步
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        //   uc.pSwitchEvent.setValue(1);
                        showDialog();
                        // dialog.show();
                    }
                })
                .subscribe(subscription);

    }


    public void jieshouyaoqing(String ids,FindItemVM vm){
        //uc.pSwitchEvent.setValue();
        model.getApi().acceptInvite(ids)
                .compose(RxUtils.bindToLifecycle(getLifecycleProvider())) // 请求与View周期同步
                .compose(RxUtils.schedulersTransformer())  // 线程调度
                //   .compose(RxUtils.exceptionTransformer())   // 网络错误的异常转换
                //    .doOnSubscribe(this) //请求与ViewModel周期同步
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        //   uc.pSwitchEvent.setValue(1);
                        showDialog();
                        // dialog.show();
                    }
                })
                .subscribe(new BaseSubscriber<BaseRep<ResMatch>>() {
                    @Override
                    public void onNext(BaseRep<ResMatch> baseRep) {
                        super.onNext(baseRep);
                        dismissDialog();
                        if (baseRep.isOk()){
                            vm.jsyqBtnVisibility.set(View.GONE);
                            vm.ypdBtnVisibility.set(View.VISIBLE);

                            Bundle bd= new Bundle();
                            bd.putString("data", GsonUtil.toJson(baseRep.getData()));
                            startContainerActivity(MatchFragment.class.getCanonicalName(),bd);
                            int pos =  observableList.indexOf(vm);
                            vm.updateNext(pos);
                        }else {
                            RxToast.showToastShort(baseRep.getMsg());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        dismissDialog();
                        //   uc.pSwitchEvent.setValue(2);
                        e.printStackTrace();
                        RxToast.showToastShort("网络出现故障");
                    }

                    @Override
                    public void onComplete() {
                        //   dismissDialog();
                    }

                });

    }


    public void addlookeduser(int pos){
        //uc.pSwitchEvent.setValue();
        if (pos >=observableList.size() ){
            return;
        }
        FindItem data = ((FindItemVM)observableList.get(pos)).item;
        if(data == null || data.getBaseInfo() ==null){
            return;
        }
        String uid = data.getBaseInfo().getId();
        BaseSubscriber subscription =  new BaseSubscriber<BaseRep>() {
            @Override
            public void onNext(BaseRep baseRep) {
                super.onNext(baseRep);
                if (baseRep.isOk()){

                }else {
                  //  RxToast.showToastShort(baseRep.getMsg());
                }

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {
                //   dismissDialog();
            }

        };

        model.getApi().addlookeduser(uid)
                .compose(RxUtils.bindToLifecycle(getLifecycleProvider())) // 请求与View周期同步
                .compose(RxUtils.schedulersTransformer())  // 线程调度
                //   .compose(RxUtils.exceptionTransformer())   // 网络错误的异常转换
                //    .doOnSubscribe(this) //请求与ViewModel周期同步
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {

                        // dialog.show();
                    }
                })
                .subscribe(subscription);

    }



    public void startChat(String id){
        //uc.pSwitchEvent.setValue();
        uc.startChat.setValue(id);

    }



    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}
